clear all
global system "linux"

if "${system}" == "linux" {
	global code "/"
	global s "/"
}

run "${code}${s}_set-path.do"
cd "${code}/tba_elig"

args index 

cap log close _all
log using "${log}/log-ob-cll-`index'", name("log`index'") text replace

local MaxDepvar= 5
local MaxWindow = 3
local MaxNumPoly = 3
local MaxSample = 2

local DepvarType = ceil(`index'/ `MaxWindow'/ `MaxNumPoly'/ `MaxSample')
if `DepvarType' == 1 local depvar "HiBal"
if `DepvarType' == 2  local depvar "rate"
if `DepvarType' == 3  local depvar "point"
if `DepvarType' == 4  local depvar "iv_rate"
if `DepvarType' == 5  local depvar "iv_point"

local index1 = `index' - (`DepvarType' - 1)* `MaxWindow'* `MaxNumPoly'* `MaxSample'
local WindowType = ceil(`index1'/ `MaxNumPoly'/ `MaxSample')

local w = `WindowType'* 50  


local index2 = `index1' - (`WindowType' - 1)* `MaxNumPoly'* `MaxSample'
local poly = ceil(`index2'/ `MaxSample')

local index3 = `index2' - (`poly' - 1)* `MaxSample'
local Sample = `index3'
if `Sample' == 1 local If
if `Sample' == 2 local If "if gse_id==1"

***** regression
use  "${hpc}/ob-cll-cleaned.dta" if year <= 2013 & abs(PaboveC) <= `w', clear

global controls "lockperiod*0 c.fico##c.fico##c.fico"
global FEs "FE1=i.zip FE2=i.lockdate FE3=i.LLPA FE4=i.lender"

if regexm("`depvar'" , "iv_") == 0 {
	
	global poly1 "PaboveC 1.HiP#c.PaboveC1"
	global poly2 "$poly1 PaboveC2 1.HiP#c.PaboveC2"
	global poly3 "$poly2 PaboveC3 1.HiP#c.PaboveC3"
	
	cap drop FE*
	local depvar2 "`depvar'"
	reghdfe `depvar2' ${poly`poly'} $controls, a($FEs) vce(robust)
}
	
if regexm("`depvar'" , "iv_") > 0 {
	global poly1 ""
	global poly2 "c.PaboveC#c.PaboveC c.PaboveC#c.PaboveC#1.HiP"
	global poly3 "$poly2 c.PaboveC#c.PaboveC#c.PaboveC c.PaboveC#c.PaboveC#c.PaboveC#1.HiP"
		
	local depvar2 `=substr("`depvar'", 4, .)'
	cap drop FE*
	reghdfe `depvar2' PaboveC ${poly`poly'}  $controls  (HiBal = slope) `If', a($FEs) vce(robust)
}	

estimate save "${Estimates}/reg-ob-cll-`depvar'-poly`poly'-window`w'-Sample`Sample'", replace


**** Figure
if `poly'==3 & `w' == 150 & regexm("`depvar'" , "iv") == 0 & `Sample' == 1 {
	
	predict resid, r 
	local polyn "${poly`poly'}"
	foreach z in `polyn' {
		replace resid = resid + _b[`z']* (`z')
	}

	su `depvar'
	replace resid = resid + `r(mean)'
	
	preserve
		collapse resid if year<= `Year', by(bin) fast
		twoway scatter resid bin, xline(0) ytitle("") ylabel(, angle(0)) xlabel(-150(50)150)
		graph export "${figure}/rdplot-ob-cll-`depvar'.pdf", replace
	restore
	drop resid  
}
